<?php

class Exam_IndexController extends Core_Controller_Action_Standard {
	public function indexAction() {
	   
        $this->_helper->content
         //   ->setNoRender()
            ->setEnabled();
	}
	public function createAction() {
		if( !$this->_helper->requireUser->isValid() ) return;
		if( !$this->_helper->requireAuth()->setAuthParams('exam', null, 'create')->isValid() ) return;
		// Get navigation
		$this->view->navigation = $navigation = Engine_Api::_()->getApi( 'menus', 'core' )
								->getNavigation('exam_main', array(), 'exam_main_exam');
								
		$this->view->subnavigation = $subnavigation = Engine_Api::_()->getApi( 'menus', 'core' )
								->getNavigation('exam_main_exam', array(), 'exam_main_exam_create');
		$viewer = Engine_Api::_()->user()->getViewer();

                $this->view->tinyMce()->setOptions(Engine_Api::_()->exam()->initTinyMCE());

		// Get form
		$this->view->form = $form = new Exam_Form_Exam_Create();
		
	    // Not post/invalid
	    if( !$this->getRequest()->isPost() ) {
	      return;
	    }
	    
	    
	    if( !$form->isValid($this->getRequest()->getPost()) ) {
	    	$values = $form->getValues();
	    	$this->view->values = $values;
	      	return;
	    }
	    
	    // Process
	    $values = $form->getValues();
	    $values['owner_id'] = $viewer->getIdentity();
	    if($values['is_limited'] == 0)
	    	$values['duration'] = 0;

	     $values = array_merge($values,array(
             'creation_date'=>date('Y-m-d h:i:s'),
             'modified_date'=>date('Y-m-d h:i:s')
         ));	

    	// Convert times
    	if($values['is_forever'] != 0){
		    $oldTz = date_default_timezone_get();
		    date_default_timezone_set($viewer->timezone);
		    $start = strtotime($values['starttime']);
		    $end = strtotime($values['endtime']);
		    date_default_timezone_set($oldTz);
		    $values['starttime'] = date('Y-m-d H:i:s', $start);
		    $values['endtime'] = date('Y-m-d H:i:s', $end);
    	}
    	
	    //begin
		$db = Engine_Api::_()->getItemTable('exam')->getAdapter();
		$db->beginTransaction();
		
		try {
			  // Create exam
		      $table = Engine_Api::_()->getDbtable('exams', 'exam');
		      $exam = $table->createRow();
		
		      $exam->setFromArray($values);
		      $exam->save();
		      
		      // Add photo
		      if( !empty($values['photo']) ) {
		        $exam->setPhoto($form->photo);
		      } 
		      
		      // Set auth
		      $auth = Engine_Api::_()->authorization()->context;
		      
		      $roles = array('owner', 'member', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');
		
		      if( empty($values['auth_test']) ) {
		        $values['auth_test'] = 'everyone';
		      }
		
		      if( empty($values['auth_comment']) ) {
		        $values['auth_comment'] = 'everyone';
		      }
		
		      $viewMax = array_search($values['auth_view'], $roles);
		      $commentMax = array_search($values['auth_comment'], $roles);
		
		      foreach( $roles as $i => $role ) {
		        $auth->setAllowed($exam, $role, 'view',    ($i <= $viewMax));
		        $auth->setAllowed($exam, $role, 'comment', ($i <= $commentMax));
		      }
		      
		      $exam->save();
				
			$db->commit();
		} catch ( Exception $e ) {
			$db->rollBack ();
//			throw $e;
		}
		$this->_helper->redirector->gotoRoute ( array ('action' => 'qtmanage', 'exam_id' => $exam->exam_id), 'exam_specific', true );
	}
	
	public function xmlcategoriesAction() {
		// root
		$isRoot = $this->_getParam('root', 0);
	
		// root name
		$rootName = $this->_getParam('rootName', 'Root');
	
		// check
		if (!is_numeric($isRoot)) {
			$isRoot = 0;
		}
		$isRoot = intval($isRoot);
		if ($isRoot != 1) {
			$isRoot = 0;
		}
        
		// selected
		$selectedId = $this->_getParam('selected');
	
		// check
		if (!is_null($selectedId) && !is_numeric($selectedId)) {
			$selectedId = null;
		}
	
		if (is_numeric($selectedId)) {
			$selectedId = intval($selectedId);
		}
	
		// excluded
		$excludedId = $this->_getParam('excluded');
	
		// check
		if (!is_null($excludedId) && !is_numeric($excludedId)) {
			$excludedId = null;
		}
	
		if (is_numeric($excludedId)) {
			$excludedId = intval($excludedId);
		}
	
		// get tree
		$tree = Engine_Api::_()
		->getApi('category', 'exam')
		->getExamCategoryTree();
	
		// get XML string
		$xmlContent = Engine_Api::_()
		->getApi('category', 'exam')
		->getExamTreeXML($tree, $isRoot, $selectedId, $excludedId, $rootName);
		// set response
		$this->getResponse()
		->setHeader('Content-Type', 'text/xml; charset=utf-8')
		->setBody($xmlContent);
	
		// disable layout, view renderer
		$this->_helper->layout->disableLayout(true);
		$this->_helper->viewRenderer->setNoRender(true);
	
		return;
	}
     public function uploadPhotoAction()
      {
        if (!$this->_helper->requireUser()->isValid()) return;
        if( !isset($_FILES['Filedata']) ) return;

            $viewer = Engine_Api::_()->user()->getViewer();
            $_module = $this->module;
            $mainUrl = Engine_Api::_()->exam()->createPhoto($_FILES['Filedata'], $viewer->getIdentity(), $viewer->getIdentity(), 'exam', 'user')->storage_path;
            echo Engine_Api::_()->exam()->imageTab($this->view->baseUrl(), $mainUrl);
        exit;
      }
}
